package com.net.xpay.web.controller.common;

import com.alipay.api.AlipayApiException;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.model.CommonAutoPayModel;
import com.net.xpay.core.service.auto.AutoPayService;
import com.net.shard.ShardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 2020/6/28 09:46

 */
@RestController
@Slf4j
@RequestMapping("/common/auto-pay")
@Api(tags = "公共/自动付充值", description = "公共 自动付充值 net")
public class CommonAutoPayController {



    @Autowired
    private AutoPayService autoPayService;

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserShardManager userShardManager;


    /**
     * 发起打款
     */
    @ApiOperation(value = "发起打款")
    @PostMapping("/trans")
    @ResponseBody
    public ResultData<String> transAutoPay(@RequestBody CommonAutoPayModel payModel) throws AlipayApiException {
        if (Strings.isNullOrEmpty(payModel.getUid())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "付款链接有误");
        }

        User user = userManager.findByUid(payModel.getUid());
        if (user == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "付款链接有误");
        }
        Preconditions.checkArgument(user.getUid().equals(payModel.getUid()));

        UserShard userShard = userShardManager.getById(user.getId());
        try {
            ShardUtil.setShardContext(userShard.getShardId());
            return new ResultData<>(autoPayService.autoPay(user, payModel));
        } finally {
            ShardUtil.cleanShardContext();
        }


    }


}
